package study.netty.websocket.support.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();

        //用户行为触发器，用做心跳检测
        pipeline.addLast(new IdleStateHandler(30, 0, 0));
        //将请求和应答消息解码为HTTP消息
        pipeline.addLast(new HttpServerCodec());
        // 分块向客户端写数据，防止发送大文件时导致内存溢出， channel.write(new ChunkedFile(new
        pipeline.addLast(new ChunkedWriteHandler());
        // 将HttpMessage和HttpContents聚合到一个完成的
        // FullHttpRequest或FullHttpResponse中,具体是FullHttpRequest对象还是FullHttpResponse对象取决于是请求还是响应
        // 需要放到HttpServerCodec这个处理器后面
        pipeline.addLast(new HttpObjectAggregator(10240));
        // 数据压缩扩展，当添加这个的时候WebSocketServerProtocolHandler的第三个参数需要设置成true
//		pipeline.addLast(new WebSocketServerCompressionHandler());
        // 聚合 websocket 的数据帧，因为客户端可能分段向服务器端发送数据
        pipeline.addLast(new WebSocketFrameAggregator(10 * 1024 * 1024));
        //服务器端向外暴露的 web socket 端点，当客户端传递比较大的对象时，maxFrameSize参数的值需要调大
        pipeline.addLast(new WebSocketServerProtocolHandler("/chat", null, true, 10485760));
        // 自定义处理器 - 处理 web socket 二进制消息
        pipeline.addLast(new ChatHandler());
    }
}
